<template>
  <div class="app-car-container">
    <CustomContent>
      <template v-slot:body>
        <el-row style="position:relative;z-index:1;">
          <el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px">
            <MmvTitle title="基本信息"></MmvTitle>
            <el-col :sm="24" :md="8">
              <el-form-item label="门店名称" prop="storeName">
                <el-input v-model="form.storeName" placeholder="请输入门店名称" clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="门店联系人" prop="contactName">
                <el-input v-model="form.contactName" placeholder="请输入门店联系人" clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :sm="24"></el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="form.contactPhone" placeholder="请输入联系电话" clearable :style="{ width: '100%' }"
                  maxlength="11"></el-input>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="门店地址" prop="areaName">
                <el-cascader clearable size="large" ref="myCascader" style="width: 100%" :options="options"
                  v-model="selectedOptions" placeholder="请选择省/市/区" @change="handleChange"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :sm="24"></el-col>
            <el-col :sm="24" :md="16">
              <el-form-item label="经纬度" prop="storeLon">
                <el-input v-show="form.storeLon" v-model="form.storeLon" placeholder="经度" clearable readonly
                  :style="{ width: 'calc(50% - 100px)' }" readonly="readonly">
                  <template slot="prepend">经度</template>
                </el-input>
                <span v-show="form.storeLon">--</span>
                <el-input v-show="form.storeLon" v-model="form.storeLat" placeholder="纬度" clearable readonly
                  :style="{ width: 'calc(50% - 100px)' }" readonly="readonly">
                  <template slot="prepend">经度</template> </el-input>
                <el-button type="primary" icon="el-icon-search" size="medium"
                  style="position:relative;z-index:99;margin-left:12px;" @click="positionShowFun">
                  地图选点</el-button>
              </el-form-item>
            </el-col>
            <el-col :sm="24"></el-col>
            <el-col :sm="24" :md="8" v-show="form.storeLon">
              <el-form-item label="详细地址">
                <el-input v-model="form.addrDetail" placeholder="请输入详细地址" clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :sm="24"></el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="营业时间" prop="businessStartTime">
                <el-time-picker v-model="form.businessStartTime" format="HH:mm" value-format="HH:mm"
                  :style="{ width: 'calc(50% - 9px)' }" placeholder="开始时间" clearable>
                </el-time-picker>
                --
                <el-time-picker v-model="form.businessEndTime" format="HH:mm" value-format="HH:mm"
                  :style="{ width: 'calc(50% - 9px)' }" placeholder="结束时间" clearable>
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="实景图" prop="storeImage">
                <ImageUpload @on-success="storeImageSuccess" v-model="form.storeImage" :limit="6"
                  @on-remove="storeImageRemove" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <MmvTitle title="运营信息"></MmvTitle>
            </el-col>
            <el-col :sm="24" :md="18" :lg="16" class="table-padding">
              <el-collapse accordion style="
                  border: 1px solid rgb(242 242 242);
                  text-align: left;
                  border-radius: 4px;
                  background-color: rgb(242 242 242);
                ">
                <el-row style="padding: 10px 20px; box-sizing: boder-box">
                  <el-col :span="24" style="font-size: 18px">
                    <div style="
                        color: rgb(51 51 51);
                        margin: 10px 10px;
                        letter-space: 2px;
                      ">
                      <i class="el-icon-info"></i> 运营信息指南：
                    </div>
                  </el-col>
                  <el-col :span="24">
                    <div style="
                        color: rgb(163 155 155);
                        line-height: 2em;
                        text-indent: 4em;
                        letter-space: 2px;
                      ">
                      运营信息指门店送车上门/接客到店服务范围，设置后可根据范围内/范围外客户收取不同送车服务费
                    </div>
                    <div style="
                        color: rgb(66 63 63);
                        line-height: 2em;
                        text-indent: 4em;
                        letter-space: 2px;
                      ">
                      门店运营设置关系到客户查看门店服务收费明细，塑造良好的门店服务形象，请慎重填写规则。
                    </div>
                  </el-col>
                </el-row>
              </el-collapse>
            </el-col>
            <el-col :span="24"></el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="服务范围/km" prop="serverScope" label-width="200px">
                <el-input v-model="form.serverScope" placeholder="输入以门店为中心的半径" clearable :style="{ width: '100%' }"
                  maxlength="11"></el-input>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="范围内服务费/元" prop="serviceChargeScope" label-width="150px">
                <el-input v-model="form.serviceChargeScope" placeholder="输入金额/元" clearable :style="{ width: '100%' }"
                  maxlength="11"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24"></el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="超范围收费标准km/元" prop="standardFees" label-width="200px">
                <el-input v-model="form.standardFees" placeholder="请输入km/元" clearable :style="{ width: '100%' }"
                  maxlength="11"></el-input>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="8">
              <el-form-item label="城市封顶费用/元" prop="cappingFees" label-width="150px">
                <el-input v-model="form.cappingFees" placeholder="请输入金额/元" clearable :style="{ width: '100%' }"
                  maxlength="11"></el-input>
              </el-form-item>
            </el-col>


            <el-col :span="24">
              <MmvTitle title="其他规则"></MmvTitle>
            </el-col>
            <el-col :sm="24" :md="24">
              <el-form-item label="最大提前预约天数" prop="advanceAppointmentDays" label-width="150px"
                class="advanceAppointmentDays">
                <div style="display: flex;justify-content: flex-start; align-items: center;">
                  <el-radio v-model="limitation" :label="1" @input="form.advanceAppointmentDays = null">不限</el-radio>
                  <el-radio v-model="limitation" :label="2">&nbsp;</el-radio>
                  <el-input v-model="form.advanceAppointmentDays" placeholder="请输入" :disabled="limitation === 1"
                    @keyup.native="form.advanceAppointmentDays = minZero(oninput(form.advanceAppointmentDays, 0))"
                    style="width: 100px;margin-left: -25px"></el-input>天
                </div>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>

      </template>
      <template v-slot:footer>
        <el-button type="info" plain @click.native="close">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>

      </template>
    </CustomContent>

    <!--地图选点 -->
    <el-dialog title="地图选点" :visible.sync="positionShow" width="800px" append-to-body :closeOnClickModal="false">
      <position :showText="false" @input="getMapInfo" :areaName="form.areaName" v-if="positionShow" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="positionShow = false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStore,
  getStore,
  delStore,
  addStore,
  updateStore,
  exportStore,
  editAvailable,
  getAllStore,
  getCityCode,
} from '@/api/store/store'
import { treeselect } from '@/api/system/dept'
import { regionData, CodeToText } from 'element-china-area-data' // 引入三级联动
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import CustomContent from '@/components/custom/content.vue'
import position from '../../components/BaiduMap/baiduMapSeach.vue'
export default {
  name: 'storeAdd',
  dicts: [
  ],
  components: {
    MmvTitle,
    CustomContent,
    position
  },
  data() {
    const validateAreaName = (rule, value, callback) => {
      if (!this.form.areaName) {
        callback(new Error('请选择省市区'))
      } else {
        callback()
      }
    }
    const validateImage = (rule, value, callback) => {
      if (!this.form.storeImage) {
        callback(new Error('请选择一个实景图'))
      } else {
        callback()
      }
    }
    const validateTime = (rule, value, callback) => {
      if (!this.form.businessStartTime) {
        callback(new Error('请选择营业开始时间'))
      } else if (!this.form.businessEndTime) {
        callback(new Error('请选择营业结束时间'))
      } else {
        callback()
      }
    }
    const valiaDays = (rule, value, callback) => {
      if (this.limitation === 1) {
        callback()
      } else if (this.form.advanceAppointmentDays != 0 && !this.form.advanceAppointmentDays) {
        callback(new Error('请输入最大提前预约天数'))
      } else {
        callback()
      }
    }
    return {
      limitation: 1,
      positionShow: false,
      submitLoading: false,
      // businessTime: ['08:00', '22:00'],
      selectedOptions: [],
      deptOptions: [],
      storeOptions: [],
      // 选择地区数据
      options: [], //regionData省市区数据
      form: {
        storeType: 1,
        advanceAppointmentDays: null,
        serviceMode: 1,
        storeClass: 1,
        storeName: undefined,
        companyId: undefined,
        contactName: undefined,
        contactPhone: undefined,
        addrDetail: undefined,
        storeLon: undefined,
        storeLat: undefined,
        field118: undefined,
        storeImage: null,
        businessStartTime: '08:00',
        businessEndTime: '22:00',
      },
      rules: {
        storeType: [
          {
            required: true,
            message: '门店类型不能为空',
            trigger: 'change',
          },
        ],
        serviceMode: [
          {
            required: true,
            message: '服务模式不能为空',
            trigger: 'change',
          },
        ],
        storeClass: [
          {
            required: true,
            message: '门店分类不能为空',
            trigger: 'change',
          },
        ],
        storeName: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'change',
          },
        ],
        companyId: [
          {
            required: true,
            message: '请选择所属部门/门店',
            trigger: 'change',
          },
        ],
        contactName: [
          {
            required: true,
            message: '请输入联系人',
            trigger: 'change',
          },
        ],
        contactPhone: [
          { required: true, message: '请输联系人电话' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'change',
          },
        ],
        areaName: [
          {
            required: true,
            message: '请选择省市区',
            trigger: 'change',
            validator: validateAreaName,
          },
        ],
        addrDetail: [
          {
            required: true,
            message: '请输入详细地址',
            trigger: 'blur',
          },
        ],
        businessStartTime: [
          {
            required: true,
            trigger: 'blur',
            validator: validateTime,
          },
        ],
        storeLon: [
          {
            required: true,
            message: '请地图选点',
            trigger: 'change',
          },
        ],
        storeLat: [
          {
            required: true,
            message: '请地图选点',
            trigger: 'change',
          },
        ],
        serverScope: [
          { required: true, message: '请输入服务范围' },
          {
            validator(rule, value, callback) {
              if (!value || Number(value) == 0) {
                return callback()
              }
              if (!Number(value)) {
                callback(new Error('服务范围输入有误'))
              }
              if (Number(value) < 0) {
                callback(new Error('服务范围输入有误'))
              }
              return callback()
            },
          },
        ],
        serviceChargeScope: [
          {
            validator(rule, value, callback) {
              if (!value || Number(value) == 0) {
                return callback()
              }
              if (!Number(value)) {
                callback(new Error('范围内服务费输入有误'))
              }
              if (Number(value) < 0) {
                callback(new Error('范围内服务费输入有误'))
              }
              return callback()
            },
          },
        ],
        standardFees: [
          {
            validator(rule, value, callback) {
              if (!value || Number(value) == 0) {
                return callback()
              }
              if (!Number(value)) {
                callback(new Error('超范围收费标准输入有误'))
              }
              if (Number(value) < 0) {
                callback(new Error('超范围收费标准输入有误'))
              }
              return callback()
            },
          },
        ],
        cappingFees: [
          {
            validator(rule, value, callback) {
              if (!value || Number(value) == 0) {
                return callback()
              }
              if (!Number(value)) {
                callback(new Error('城市封顶费用输入有误'))
              }
              if (Number(value) < 0) {
                callback(new Error('城市封顶费用输入有误'))
              }
              return callback()
            },
          },
        ],

        advanceAppointmentDays: [
          {
            trigger: 'blur',
            validator: valiaDays,
          },
        ],
      },
    }
  },
  created() {
    this.reset()
    this.getTreeselect()
    this.getAllStore()
    this.getCityCode()
    if (this.$route.query.storeId) {
      this.form.storeId = this.$route.query.storeId
      this.handleDetail(this.$route.query.storeId)
    }
  },
  methods: {
    minZero(num) {
      return Number(num) < 0 ? 0 : num
    },
    // 表单重置
    reset() {
      this.form = {
        storeId: null,
        storeName: null,
        storeType: 1,
        serviceMode: 1,
        storeClass: 1,
        contactName: null,
        contactPhone: null,
        companyId: null,
        companyName: null,
        label: null,
        provinceId: null,
        provinceName: null,
        cityId: null,
        cityName: null,
        areaId: null,
        areaName: null,
        storeLon: null,
        storeLat: null,
        addrDetail: null,
        businessStartTime: '08:00',
        businessEndTime: '22:00',
        delFlag: null,
        isAvailable: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        tenantId: null,
        deptId: null,
        advanceAppointmentDays: null,
      }
      this.selectedOptions = []
      this.resetForm('elForm')
    },
    /** 修改按钮操作 */
    handleDetail(storeId) {
      this.reset()
      this.getTreeselect()
      this.getAllStore()
      this.getCityCode()
      getStore(storeId).then((response) => {
        this.form = response.data
        // this.businessTime = [
        //   response.data.businessStartTime,
        //   response.data.businessEndTime,
        // ]

        if (response.data.advanceAppointmentDays > -1) {
          this.form.advanceAppointmentDays = response.data.advanceAppointmentDays
          this.limitation = 2
        } else {
          this.form.advanceAppointmentDays = null
          this.limitation = 1
        }


        this.selectedOptions = [
          response.data.provinceId,
          response.data.cityId,
          response.data.areaId,
        ]
        this.$forceUpdate()
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data
      })
    },
    /** 查询部门下拉树结构 */
    getAllStore() {
      getAllStore({ storeType: 1 }).then((response) => {
        this.storeOptions = response.data
      })
    },
    getCityCode() {
      getCityCode().then((res) => {
        let provinceIds = res.data.provinceIds
        let cityIds = res.data.cityIds
        let arr = []
        for (let var1 of regionData) {
          if (provinceIds.indexOf(var1.value) != -1) {
            let children = []
            for (let var2 of var1.children) {
              if (cityIds.indexOf(var2.value) != -1) {
                children.push(var2)
              }
            }
            let province = {
              label: var1.label,
              value: var1.value,
              children: children,
            }
            arr.push(province)
          }
        }
        this.options = arr
      })
    },
    // 省市区三级
    handleChange(value) {
      var nodes = this.$refs['myCascader'].getCheckedNodes()
      if (nodes && nodes[0]) {
        var node = nodes[0]
        this.form.provinceId = node.parent.parent.value
        this.form.provinceName = node.parent.parent.label
        this.form.cityId = node.parent.value
        this.form.cityName = node.parent.label
        if ('市辖区' == node.parent.label) {
          this.form.cityName = node.parent.parent.label
        } else {
          this.form.cityName = node.parent.label
        }
        this.form.areaId = node.value
        this.form.areaName = node.label
      } else {
        this.form.provinceId = null
        this.form.provinceName = null
        this.form.cityId = null
        this.form.cityName = null
        this.form.areaId = null
        this.form.areaName = null
      }
    },
    // 上传成功门店回调
    storeImageSuccess(res) {
      this.form.storeImage = res.fileName
      this.$refs['form'].validateField('storeImage')
    },
    // 删除门店图片
    storeImageRemove(file) {
      this.form.storeImage = null
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (valid) {
          try {
            this.submitLoading = true
            let data = {
              ...this.form,
              advanceAppointmentDays: this.form.advanceAppointmentDays ? this.form.advanceAppointmentDays : -1
            }
            if (this.form.storeId != null) {
              updateStore(data)
                .then((response) => {
                  this.$modal.msgSuccess('修改成功')
                  this.submitLoading = false
                  this.close()
                })
                .catch((error) => {
                  this.$modal.msgSuccess('修改失败')
                  this.submitLoading = false
                })
            } else {
              addStore(data)
                .then((response) => {
                  this.$modal.msgSuccess('新增成功')
                  this.close()
                  this.submitLoading = false
                })
                .catch((error) => {
                  this.$modal.msgSuccess('新增失败')
                  this.submitLoading = false
                })
            }
          } catch (error) {
            this.submitLoading = false
          }
        }
      })
    },
    getMapInfo(res) {
      this.form.storeLon = JSON.parse(res).lng
      this.form.storeLat = JSON.parse(res).lat
      this.form.addrDetail = JSON.parse(res).address
    },
    positionShowFun() {
      this.positionShow = true;
    },
    close() {
      // 关闭页面
      this.reset()
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },
  },
}
</script>
<style>
.advanceAppointmentDays .el-form-item__label:before {
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
</style>
